import string
from scenario_processing import read_scenarios
from journal_processing import process_journal_file

def find_usecase(scenarios, jfile) :
    for usecase in scenarios :
        if usecase in jfile :
            return usecase
    print "WARNING!!"*3, "No usecase found to match journal file " + jfile + " returning hardcoded value!"
    return "Example_Europa1_11_0GBps_s"

def parse_bandwidth_results(outdir) :
    bwresults = {}
    for l in open(outdir+"/bandwidth_results.txt") :
        flds = l.split()
        title = flds[0]
        bwresults[title] = {"RD":None, "WR":None, "any":None}
        for fi in range(1, len(flds), 3) :
            mode, num = flds[fi], flds[fi+2]
            try :
                bwresults[title][mode] = string.atof(num)
            except ValueError :
                bwresults[title][mode] = None
    return bwresults

def find_matching_initiator(key, allkeys) :
    for ak in allkeys :
        if ak == key[0:len(ak)] :
            return ak
    return None

if __name__=="__main__" :
    all_initiators, scenarios = read_scenarios()

    jfile = "/home/local_admin/Downloads/JP/jp/Example_Europa1_11_0GBps_DDR4_32x2_1087MHz_Tight_57pc_s_j"
    usecase = find_usecase(scenarios, jfile)
    requested_bandwidths = scenarios[usecase]
    outdir = "/tmp"
    process_journal_file(jfile, outdir)
    measured_bandwidths = parse_bandwidth_results(outdir)
    ofp = open(outdir + "/bandwidth_comparison.txt", 'w')
    warnings = []
    for initiator, mes_bw in measured_bandwidths.items() :
        init = find_matching_initiator(initiator, requested_bandwidths.keys())
        if init is None :
            msg = "WARNING!!"*3 + " Could not find matching initiator from scenarios for " + str(initiator) + "   " + str(mes_bw)
            warnings.append((msg,initiator))
            print msg
            continue
        else :
            print "Matched initiator from scenarios : ", init, initiator
        req_rd, req_wr = requested_bandwidths[init]
        print initiator, init, mes_bw, req_rd, req_wr
        mes_rd, mes_wr = mes_bw["RD"], mes_bw["WR"]
        def bw_fail_diff(req, meas) :
            fmt = "%-20s"
            if req == 0 :
                return False, fmt % "0 (0%)"
            if meas == None :
                return False, fmt % "None"
            diffstr = fmt % ("%6.5f (%2.1f%%)" % ((meas-req), 100.*(meas-req)/req))
            if req > meas :
                return True, diffstr
            return False, diffstr
        rd_failed, diff_rd = bw_fail_diff(req_rd, mes_rd)
        wr_failed, diff_wr = bw_fail_diff(req_wr, mes_wr)
        if not rd_failed and not wr_failed :
            status = "PASS"
        elif rd_failed and wr_failed :
            status = "FAIL_BOTH"
        elif rd_failed :
            status = "FAIL_READ"
        elif wr_failed :
            status = "FAIL_WRITE"
        else :
            status = "PASS_CHECK"
        def mapper(num) :
            if num is None : return "None   "
            else : return "%6.5f" % num
        #diff_rd = differ(req_rd, mes_rd)
        #diff_wr = differ(req_wr, mes_wr)
        req_rd, req_wr, mes_rd, mes_wr = map(mapper, [req_rd, req_wr, mes_rd, mes_wr])
        msg = "%-10s %22s %18s    RD = req:%s meas=%s diff:%s   WR = req:%s meas:%s diff:%s" % (status, initiator, init, req_rd, mes_rd, diff_rd, req_wr, mes_wr, diff_wr)
        print >> ofp, msg
    for msg in sorted(warnings, key=lambda x : x[1]) :
        print >> ofp, msg[0]
    ofp.close()
